﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using WMSADBUtility;

namespace ElectronicWMSA.List.Second
{
    public partial class ShowExcel : Form
    {
        public ShowExcel()
        {
            InitializeComponent();
            DBind();
            Type dgvType1 = DGV.GetType();
            PropertyInfo pi1 = dgvType1.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
            pi1.SetValue(DGV, true, null);
        }

        int NID;

        #region 函数
        public void DBind()
        {
            string query = "select Nid,ExcelName,CreateTime from T_Excel_Log";
            DataSet ds = DBHelper.Query(query);
            DGV.DataSource = ds.Tables[0];
        }

        #endregion

        #region 按钮：退出
        private void btnExit_Click(object sender, EventArgs e)
            {
                this.Close();
            }
        #endregion

        #region 刷新
        private void update_Click(object sender, EventArgs e)
        {
            DBind();
        }
        #endregion

        private void bt_DownLoad_Click(object sender, EventArgs e)
        {

            ExcelLog_DAL bill = new ExcelLog_DAL();
            ExcelLog_Entity entity = new ExcelLog_Entity();
            entity = bill.GetEntity(NID);
            if (entity != null)
            {
                //选择文件存放的路径
                System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
                dialog.Description = "请选择你要存放的文件夹路径";
                dialog.ShowNewFolderButton = true;
                System.Windows.Forms.DialogResult result = dialog.ShowDialog();
                object paths = dialog.SelectedPath;
                string currenTimeString = DateTime.Now.ToString("yyyyMMddHHmmss");

                //文件写入
                byte[] Files = entity.ExcelFile;
                BinaryWriter bw = new BinaryWriter(File.Open((string)paths+"//"+currenTimeString+".xlsx", FileMode.OpenOrCreate));
                bw.Write(Files);
                bw.Close();
                MessageBox.Show("下载成功");

            }

        }

        
        private void DGV_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;
            //防止选中第一行报错
            if (DGV.RowCount > 0)
            {
                int rindex = e.RowIndex;

                NID = Convert.ToInt32(DGV.Rows[rindex].Cells["Nid"].Value.ToString());
            }
        }

        private void Instruction_Click(object sender, EventArgs e)
        {
            Instruction_Excel ins = new Instruction_Excel();
            ins.ShowDialog();
        }
    }
}
